/**
 * Created by houjianhui on 2017/7/17.
 */

angular.module('kasApp', ['ionic', 'kas.controllers', 'kas.services'])

    .constant('Settings', {
        Context: {
            path: contextPath,
            hostAddress: hostAddress
        }
    })
    .run(['$rootScope', '$timeout', '$state', '$location', '$ionicPopup', '$ionicActionSheet', 'Settings', function($rootScope, $timeout, $state, $location, $ionicPopup, $ionicActionSheet, Settings) {

        var date = new Date();
        var localIdsList = [];
        var serverIdList = [];
        var timerList = [];
        var callbackFunc = null;
        $rootScope.Context = Settings.Context;
        // 我的运单tab初始化默认值
        $rootScope.tabActive = 0;

        // 微信ui组件工具类
        $rootScope.WeiUI = {
            confirm: function(option) {
                var that = this;
                that.confirm.option = angular.extend({
                    title: '标题',
                    template: '确认此操作吗?',
                    cancelText: '取消',
                    okText: '确定',
                    cancelCallback: null,
                    okCallback: null
                }, option);
                that.confirm.flag = true;
                that.confirm.cancelFunc= function() {
                    that.confirm.flag = false;
                    if (that.confirm.option.cancelCallback) {
                        that.confirm.option.cancelCallback();
                    }
                };
                that.confirm.okFunc= function() {
                    that.confirm.flag = false;
                    if (that.confirm.option.okCallback) {
                        that.confirm.option.okCallback();
                    }
                };
                that.confirm.resetOption = function(option) {
                    that.confirm.option = angular.extend(that.confirm.option, option);
                };
                that.confirm.hide = function() {
                    that.confirm.flag = false;
                };
            },
            alert: function(option) {
                var that = this;
                that.alert.option = angular.extend({
                    title: '标题',
                    template: '已完成操作',
                    okText: '确定',
                    okCallback: null
                }, option);
                that.alert.flag = true;
                that.alert.okFunc= function() {
                    that.alert.flag = false;
                    if (that.alert.option.okCallback) {
                        that.alert.option.okCallback();
                    }
                };
            },
            actionSheet: function(option) {
                var that = this;
                that.actionSheet.option = angular.extend({
                    cancelText: '取消',
                    okCallback: null,
                    cancelCallback: null,
                    list: []
                }, option);
                that.actionSheet.flag = true;
                that.actionSheet.select= function(index) {
                    that.actionSheet.flag = false;
                    if (that.actionSheet.option.okCallback) {
                        that.actionSheet.option.okCallback(index);
                    }
                };
                that.actionSheet.cancelFunc= function() {
                    that.actionSheet.flag = false;
                    if (that.actionSheet.option.cancelCallback) {
                        that.actionSheet.option.cancelCallback();
                    }
                };
            },
            toast: function(option) {
                var that = this;
                that.toast.option = angular.extend({
                    title: '',
                    timeOut: 2000,
                    okCallback: null,
                }, option);
                that.toast.flag = true;
                $timeout(function() {
                    that.toast.flag = false;
                    if (that.toast.option.okCallback) {
                        that.toast.option.okCallback();
                    }
                }, that.toast.option.timeOut);
            },
            loading: function(option) {
                var that = this;
                that.loading.option = angular.extend({
                    title: '',
                }, option);
                that.loading.flag = true;
                that.loading.hide = function() {
                    that.loading.flag = false;
                };
            },
            logout: function () {
                $rootScope.WeiUI.confirm({
                    title: '提示',
                    template: '确认退出吗?',
                    cancelText: '取消',
                    okText: '确定',
                    okCallback: function () {
                        // UserService.logout().success(function(result) {
                        //     if (result.success) {
                        //         wx.closeWindow();
                        //     } else {
                        //         $rootScope.FIREFLY.toast({
                        //             title: result.message,
                        //             timeOut: 1000
                        //         });
                        //     }
                        // });
                    }
                });
            },
            search: {
                onFocusFlag: null,
                searchShowFlag: null,
                searchTextFlag: null,
                content: null,
                searchShowList: [],
                onFocus: function() {
                    this.onFocusFlag = true;
                },
                onBlur: function() {
                    this.onFocusFlag = false;
                    if (this.content) {
                        this.searchTextFlag = false;
                    } else {
                        this.searchTextFlag = true;
                    }
                },
                onInput: function() {
                    if (!this.content) {
                        this.searchShowFlag = false;
                    } else {
                        this.searchShowFlag = true;
                    }
                    this.onInputCallback();
                },
                onInputCallback: function() {},
                selectCell: function(item) {
                    this.onCancel();
                    this.selectCellCallback(item);
                },
                selectCellCallback: function(item) {},
                onCancel: function() {
                    this.content = null;
                    this.searchShowFlag = false;
                }
            }
        };

        // 微信js api调用
        $rootScope.WxJsApi = {
            // 扫码
            scanQRCode: function(callback) {
                wx.scanQRCode({
                    desc: 'scanQRCode desc',
                    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                    success: function (res) {
                        if (typeof callback === 'function') {
                            callback(res);
                        }
                    }
                });
            },
            // 上传图片
            uploadImage: function(count, callback) {
                wx.chooseImage({
                    count: count || 9, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: function (res) {
                        localIdsList = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                        if (localIdsList.length === 1) {
                            $timeout(function() {
                                wx.uploadImage({
                                    localId: localIdsList[0], // 需要上传的图片的本地ID，由chooseImage接口获得
                                    isShowProgressTips: 1,// 默认为1，显示进度提示
                                    success: function (res) {
                                        if (typeof callback === 'function') {
                                            callback(res);
                                        }
                                    }
                                });
                            }, 0);
                        } else {
                            uploadImageList(0, callback);
                        }

                        // 上传图片递归调用
                        function uploadImageList(i, callback) {
                            if (callback) {
                                callbackFunc = callback;
                            }
                            if (localIdsList.length > i) {
                                timerList.push($timeout(function () {
                                    wx.uploadImage({
                                        localId: localIdsList[i], // 需要上传的图片的本地ID，由chooseImage接口获得
                                        isShowProgressTips: 1,// 默认为1，显示进度提示
                                        success: function (res) {
                                            serverIdList.push(res.serverId);
                                            uploadImageList(i + 1);
                                        }
                                    });
                                }, 0));
                            } else {
                                for (var j = 0; j < timerList.length; j++) {
                                    $timeout.cancel(timerList[j]);
                                }
                                if (typeof callbackFunc === 'function') {
                                    callbackFunc({'serverId': serverIdList.join(',')});
                                    return;
                                }
                            }
                        };
                    }
                });
            },
            // 图片预览
            previewImage: function(index, imgList) {
                if (imgList.length > 0) {
                    wx.previewImage({
                        current: imgList[(index || 0)], // 当前显示图片的http链接
                        urls: imgList // 需要预览的图片http链接列表
                    });
                }
            },
            // 获取定位信息
            getLocation: function(callback) {
                wx.getLocation({
                    success: function (res) {
                        //var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                        //var longitude = res.longitude ; // 经度，浮点数，范围为180 ~ -180。
                        //var speed = res.speed; // 速度，以米/每秒计
                        //var accuracy = res.accuracy; // 位置精度
                        if (callback) {
                            callback(res);
                        }
                    }
                });
            },
            // 显示定位信息
            showLocation: function(option) {
                option = angular.extend({
                    latitude: 0, // 纬度，浮点数，范围为90 ~ -90
                    longitude: 0, // 经度，浮点数，范围为180 ~ -180。
                    name: '', // 位置名
                    address: '', // 地址详情说明
                    scale: 1, // 地图缩放级别,整形值,范围从1~28。默认为最大
                    infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
                }, option)
                wx.openLocation(option);
            }
        };

        // ionic弹出组件
        $rootScope.IONIC = {
            platform: {
                android: ionic.Platform.platform().toLowerCase() == 'android' ? true : false,
                ios: ionic.Platform.platform().toLowerCase() == 'ios' ? true : false,
            },
            alert: function(option) {
                var that = this;
                that.alert.option = angular.extend({
                    title: '标题',
                    template: '已完成操作',
                    okText: '确定',
                    okCallback: null
                }, option);
                initPopup(that.alert.option, function() {
                    that.alert.okFunc= function() {
                        $rootScope.closePopup(function() {
                            if (that.alert.option.okCallback) {
                                that.alert.option.okCallback();
                            }
                        });
                    };
                    $rootScope.closePopup();
                });
            },
            confirm: function(option) {
                var that = this;
                that.confirm.option = angular.extend({
                    title: '标题',
                    template: '确认此操作吗?',
                    cancelText: '取消',
                    okText: '确定',
                    cancelCallback: null,
                    okCallback: null
                }, option);
                initPopup(that.confirm.option);
            },
            actionSheet: function(option) {
                var buttons = [];
                angular.forEach(option.buttons ,function(item) {
                    buttons.push({
                        text: item.text
                    });
                });
                $ionicActionSheet.show({
                    buttons: buttons,
                    titleText: option.titleText,
                    cancelText: option.cancelText,
                    cancel: function() {
                        if (option.cancelCallback) {
                            option.cancelCallback();
                        }
                    },
                    buttonClicked: function(index) {
                        if (option.buttons && option.buttons.hasOwnProperty('length')) {
                            var len = option.buttons.length;
                            if (index + 1 <= len) {
                                var thisBtn = option.buttons[index];
                                if (thisBtn.callback) {
                                    thisBtn.callback(index);
                                }
                            }
                        }
                        return true;
                    }
                });
            }
        };

        // 我的组件
        $rootScope.FIREFLY = {
            toast: function(option) {
                var that = this;
                that.toast.option = angular.extend({
                    title: '',
                    timeOut: 3000,
                    okCallback: null,
                }, option);
                that.toast.flag = true;
                $timeout(function() {
                    that.toast.flag = false;
                    if (that.toast.option.okCallback) {
                        that.toast.option.okCallback();
                    }
                }, that.toast.option.timeOut);
            }
        };

        // 初始化popover
        function initPopup(option) {
            var buttons = [];
            if (option.hasOwnProperty('cancelText')) {
                buttons.push({
                    text: option.cancelText,
                    type: 'button-outline-kas sm',
                    onTap: function(e) {
                        if (option.cancelCallback)
                            option.cancelCallback(e);

                    }
                });
            }
            if (option.hasOwnProperty('okCallback')) {
                buttons.push({
                    text: option.okText,
                    type: 'button-kas sm',
                    onTap: function(e) {
                        if (option.okCallback)
                            option.okCallback(e);

                    }
                });
            }
            $rootScope.popUp = $ionicPopup.show({
                scope: $rootScope,
                title: option.title,
                template: '<h4 class="map">' + (option.template || '&nbsp;') + '</h4>',
                buttons: buttons,
                cssClass: 'kas-popup'
            });
            $rootScope.closePopup = function(callback) {
                $rootScope.popUp.close();
                if (callback)
                    callback();
            };
        };

        // 邀请司机
        $rootScope.invitationDriver = function(callback) {
            wx.showOptionMenu();
            var shareData = {
                title : '邀请好友注册有好礼',
                desc : '活动期间，成功邀请好友下载安装“慧运车”APP并注册、通过认证，可获得现金奖励！',
                // 分享链接
                link: $rootScope.Context.hostAddress + '/weixin/start/invitation?page=invitation-weixin&invitation=' + Tools.getMyInvitation(),
                imgUrl: $rootScope.Context.hostAddress + '/public/images/share-logo.jpg', // 分享图标
                success: function(res) {
                    $rootScope.IONIC.alert({
                        title: '企业司机邀请',
                        template: '邀请成功'
                    });
                }
            };
            wx.onMenuShareTimeline(shareData);
            wx.onMenuShareAppMessage(shareData);
            wx.onMenuShareQQ(shareData);
            wx.onMenuShareWeibo(shareData);
            wx.onMenuShareQZone(shareData);

            if (callback) {
                callback();
            }
        };

        // 设置token
        //Tools.setToken(token);
        // 设置title信息
        document.title = '中联物流';

    }])

    // 配置
    .config(['$stateProvider', '$urlRouterProvider', '$httpProvider', '$ionicConfigProvider', function($stateProvider, $urlRouterProvider, $httpProvider, $ionicConfigProvider) {

        $ionicConfigProvider.platform.android.tabs.position('bottom');
        $ionicConfigProvider.platform.android.navBar.alignTitle('center');
        $ionicConfigProvider.platform.ios.views.transition('ios');
        $ionicConfigProvider.platform.android.views.transition('android');

        $stateProvider
            .state('waybill-search', {
                url: '/waybill-search',
                templateUrl: contextPath + '/public/template/wx/waybill-search-view.html',
                controller: 'WayBillCtrl'
            });
        $urlRouterProvider.otherwise('waybill-search');

        // 使angular $http post提交和jQuery一致
        $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

        // Override $http service's default transformRequest
        $httpProvider.defaults.transformRequest = [function(data) {
            /**
             * The workhorse; converts an object to x-www-form-urlencoded serialization.
             * @param {Object} obj
             * @return {String}
             */
            var param = function(obj) {
                var query = '';
                var name, value, fullSubName, subName, subValue, innerObj, i;

                for (name in obj) {
                    value = obj[name];

                    if (value instanceof Array) {
                        for (i = 0; i < value.length; ++i) {
                            subValue = value[i];
                            fullSubName = name + '[' + i + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    } else if (value instanceof Object) {
                        for (subName in value) {
                            subValue = value[subName];
                            fullSubName = name + '[' + subName + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    } else if (value !== undefined && value !== null) {
                        query += encodeURIComponent(name) + '='
                            + encodeURIComponent(value) + '&';
                    }
                }

                return query.length ? query.substr(0, query.length - 1) : query;
            };

            return angular.isObject(data) && String(data) !== '[object File]'
                ? param(data)
                : data;
        }];
    }]);